<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="法人行"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select
                          mode="default"
                          :allowClear="true"
                          style="width: 100%"
                          @change="handleInstChange"
                          v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{r.label}}-{{r.value}}</a-select-option>
                </a-select>
<!--                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId"
                         readonly="readonly"/>-->
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: center;" v-show="queryParams.instId!=''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="queryParams.instId!=''">
      <!-- 表格区域 -->
      <div class="operator">
        <a-button v-hasPermission="['merchantGradeManager:add']" ghost type="primary" @click="addMerchantGradeManager">新增</a-button>
        <a-button v-hasPermission="['merchantGradeManager:use']" ghost type="primary" @click="stopMerchantGradeManager">停用</a-button>
        <a-button v-hasPermission="['merchantGradeManager:stop']" ghost type="primary" @click="useMerchantGradeManager">启用</a-button>
        <a-button v-hasPermission="['merchantGradeManager:cancel']" ghost type="primary" @click="cancelMerchantGradeManager">注销</a-button>
        <a-button v-hasPermission="['merchantGradeManager:import']" ghost type="primary" @click="uploadMerchantGradeManager">导入</a-button>
      </div>
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="(record,index) => {return index}"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 2600 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="merchantGradeManagerOperation" slot-scope="text, record">
          <a-icon v-hasPermission="['merchantGradeManager:edit']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                  @click="editMerchantGradeManager(record)" title="修改"></a-icon>&nbsp;
          <a-icon v-hasPermission="['merchantGradeManager:view']" type="eye" theme="twoTone" twoToneColor="#42b983"
                  @click="viewMerchantGradeManager(record)" title="查看"></a-icon>
          <a-badge v-hasNoPermission="['merchantGradeManager:edit','merchantGradeManager:view']" userStatus="warning" text="无权限"></a-badge>
        </template>

      </a-table>
      <!-- 查看 -->
      <merchant-grade-manager-info
        ref="merchantGradeManagerInfo"
        @close="handleMerchantGradeManagerInfoClose"
        :merchantGradeManagerInfoVisiable="merchantGradeManagerInfo.visiable">
      </merchant-grade-manager-info>

      <!-- 新增 -->
      <merchant-grade-manager-add
        @close="handleMerchantGradeManagerAddClose"
        @success="handleMerchantGradeManagerAddSuccess"
        :merchantGradeManagerAddVisiable="merchantGradeManagerAdd.visiable"
        :instId="this.queryParams.instId">
      </merchant-grade-manager-add>


      <!-- 修改 -->
      <merchant-grade-manager-edit
        ref="merchantGradeManagerEdit"
        @close="handleMerchantGradeManagerEditClose"
        @success="handleMerchantGradeManagerEditSuccess"
        :merchantGradeManagerEditVisiable="merchantGradeManagerEdit.visiable"
        :instId="this.queryParams.instId">
      </merchant-grade-manager-edit>

      <!-- 导入 -->
      <merchant-grade-manager-import
        @close="handleMerchantGradeManagerImportClose"
        :merchantGradeManagerImportVisiable="merchantGradeManagerImport.visiable"
        :instId="this.queryParams.instId">
      </merchant-grade-manager-import>
    </div>

    <div>
      <a-modal
        title="确认操作"
        :visible="stopShow"
        @ok="stopOk"
        @cancel="handleCancel"
      >
        {{ modalText }}
      </a-modal>
      <a-modal
        title="确认操作"
        :visible="useShow"
        @ok="useOk"
        @cancel="handleCancel"
      >
        {{ modalText }}
      </a-modal>
      <a-modal
        title="确认操作"
        :visible="cancelShow"
        @ok="cancelOk"
        @cancel="handleCancel"
      >
        {{ modalText }}
      </a-modal>
    </div>
  </a-card>
</template>

<script>
  import RangeDate from '@/components/datetime/RangeDate';
  import {mapState} from "vuex"
  import MerchantGradeManagerAdd from "./MerchantGradeManagerAdd";
  import MerchantGradeManagerEdit from "./MerchantGradeManagerEdit";
  import MerchantGradeManagerImport from "./MerchantGradeManagerImport";
  import MerchantGradeManagerInfo from "./MerchantGradeManagerInfo";

  export default {
    name: "MerchantGradeManager",
    components: {MerchantGradeManagerImport, MerchantGradeManagerEdit, MerchantGradeManagerAdd, MerchantGradeManagerInfo, RangeDate},
    data() {
      return {
        stopShow: false,
        useShow: false,
        cancelShow: false,
        modalText: '',
        advanced: false,
        merchantGradeManagerInfo: {
          visiable: false,
          data: {}
        },
        merchantGradeManagerAdd: {
          visiable: false
        },
        merchantGradeManagerEdit: {
          visiable: false
        },
        merchantGradeManagerImport: {
          visiable: false
        },

        queryParams: {
          instId: '',
        },
        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        loading: false,
        instIdData: [],
        da: [],
        mchntNoList: [],
      }
    },
    computed: {
      ...mapState({
        user: state => state.account.user,

      }),
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '商户等级代码',
          dataIndex: 'mchntLevelCode',
          scopedSlots: {customRender: 'mchntLevelCode'},
        }, {
          title: '商户等级名称',
          dataIndex: 'mchntLevelName',
          scopedSlots: {customRender: 'mchntLevelName'},
        }, {
          title: '单笔贷记限额(元)',
          dataIndex: 'singleLimitLoanMaxAmt',
          scopedSlots: {customRender: 'singleLimitLoanMaxAmt'},
        }, {
          title: '单笔借记限额(元)',
          dataIndex: 'singleLimitCreditMaxAmt',
          scopedSlots: {customRender: 'singleLimitCreditMaxAmt'},
        },{
          title: '日累计借记限额(元)',
          dataIndex: 'dayLimitLoanAmt',
          scopedSlots: {customRender: 'dayLimitLoanAmt'},
        }, {
          title: '日累计贷记限额(元)',
          dataIndex: 'dayLimitCreditAmt',
          scopedSlots: {customRender: 'dayLimitCreditAmt'},
        }, {
          title: '月累计借记限额(元)',
          dataIndex: 'monthLimitLoanAmt',
          scopedSlots: {customRender: 'monthLimitLoanAmt'},
        }, {
          title: '月累计贷记限额(元)',
          dataIndex: 'monthLimitCreditAmt',
          scopedSlots: {customRender: 'monthLimitCreditAmt'},
        }, {
          title: '日累计限额',
          dataIndex: 'dayLimitAmt',
          scopedSlots: {customRender: 'dayLimitAmt'},
        }, {
          title: '月累计限额',
          dataIndex: 'monthLimitAmt',
          scopedSlots: {customRender: 'monthLimitAmt'},
        }, {
          title: '审核状态',
          dataIndex: 'auditStatus',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return <a-tag color = "cyan" > 待提交审批 < /a-tag>
              case '01':
                return <a-tag color = "pink" > 新增-审批流程中 < /a-tag>
              case '02':
                return <a-tag color = "pink" > 新增-审批通过 < /a-tag>
              case '03':
                return <a-tag color = "pink" > 新增-审批拒绝 < /a-tag>
              case '11':
                return <a-tag color = "cyan" > 注销-审批流程中 < /a-tag>
              case '12':
                return <a-tag color = "pink" > 注销-审批通过 < /a-tag>
              case '13':
                return <a-tag color = "pink" > 注销-审批拒绝 < /a-tag>
              case '21':
                return <a-tag color = "pink" > 停用-审批流程中 < /a-tag>
              case '22':
                return <a-tag color = "cyan" > 停用-审批通过 < /a-tag>
              case '23':
                return <a-tag color = "pink" > 停用-审批拒绝 < /a-tag>
              case '31':
                return <a-tag color = "pink" > 启用-审批流程中 < /a-tag>
              case '32':
                return <a-tag color = "pink" > 启用-审批通过 < /a-tag>
              case '33':
                return <a-tag color = "cyan" > 启用-审批拒绝 < /a-tag>
              case '41':
                return <a-tag color = "pink" > 修改-审批流程中 < /a-tag>
              case '42':
                return <a-tag color = "pink" > 修改-审批通过 < /a-tag>
              case '43':
                return <a-tag color = "pink" > 修改-审批拒绝 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '待提交审批', value: '00'},
            {text: '新增-审批流程中', value: '01'},
            {text: '新增-审批通过', value: '02'},
            {text: '新增-审批拒绝', value: '03'},
            {text: '注销-审批流程中', value: '11'},
            {text: '注销-审批通过', value: '12'},
            {text: '注销-审批拒绝', value: '13'},
            {text: '停用-审批流程中', value: '21'},
            {text: '停用-审批通过', value: '22'},
            {text: '停用-审批拒绝', value: '23'},
            {text: '启用-审批流程中', value: '31'},
            {text: '启用-审批通过', value: '32'},
            {text: '启用-审批拒绝', value: '33'},
            {text: '修改-审批流程中', value: '41'},
            {text: '修改-审批通过', value: '42'},
            {text: '修改-审批拒绝', value: '43'}
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.auditStatus || null,
          onFilter: (value, record) => record.auditStatus.includes(value)
        }, {
          title: '启用状态',
          dataIndex: 'status',
          customRender: (text, row, index) => {
            switch (text) {
              case 'Y':
                return <a-tag color = "cyan" > 启用 < /a-tag>
              case 'N':
                return <a-tag color = "pink" > 停用 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '启用', value: 'Y'},
            {text: '停用', value: 'N'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.status || null,
          onFilter: (value, record) => record.status.includes(value)
        }, {
          title: '操作',
          dataIndex: 'merchantGradeManagerOperation',
          fixed: 'right',
          scopedSlots: {customRender: 'merchantGradeManagerOperation'}
        }]
      }
    },
    mounted() {
      this.$get('admin/upmporg/getInstList').then((r) => {
        this.instIdData = r.data
      })
    },
    methods: {
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },

      handleInstChange(value) {
        this.queryParams.instId = value;
        if (typeof(value) != "undefined" && value != "") {
          let params = {
          instId: value
                }
          // params.instId = value;
          this.$get('/admin/quota/merchantGradeManager/getAddMerLevelInfos', {...params}).then((r) => {
            this.dataSource = r.data.rows;
            this.search();
          })
        }
      },
      handleMerchantGradeManagerEditClose() {
        this.merchantGradeManagerEdit.visiable = false
      },
      handleMerchantGradeManagerEditSuccess() {
        this.merchantGradeManagerEdit.visiable = false
        this.$message.success('修改成功')
        this.search()
      },

      handleMerchantGradeManagerImportClose() {
        this.merchantGradeManagerImport.visiable = false
        this.search()
      },

      handleMerchantGradeManagerAddClose() {
        this.merchantGradeManagerAdd.visiable = false
      },
      handleMerchantGradeManagerAddSuccess() {
        this.merchantGradeManagerAdd.visiable = false
        this.$message.success('添加成功')
        this.search()
      },


      viewMerchantGradeManager(record) {
        this.$refs.merchantGradeManagerInfo.setMerchantGradeManagerFormValues(record)
        this.merchantGradeManagerInfo.visiable = true
      },
      handleMerchantGradeManagerInfoClose() {
        this.merchantGradeManagerInfo.visiable = false
      },
      editMerchantGradeManager(record) {
        if (record.status === '02' ) {
          this.$message.warning('停用的数据不允许再停用')
        } else {
          this.$refs.merchantGradeManagerEdit.setMerchantGradeManagerFormValues(record)
          this.merchantGradeManagerEdit.visiable = true
        }
      },
      addMerchantGradeManager() {
        this.merchantGradeManagerAdd.visiable = true
      },
      uploadMerchantGradeManager() {
        this.merchantGradeManagerImport.visiable = true
      },

      stopMerchantGradeManager() {
        if (!this.selectedRowKeys.length) {
          this.$message.warning('请选择需要停用的记录')
          return;
        }
        if (this.selectedRowKeys.length > 1) {
          this.$message.warning('请选择一条需要停用的记录')
          return;
        }
        let selectedIndex
        this.dataSource.map((val, index)=>{
          if(val.notDiffAcctId === this.selectedRowKeys[0]) return selectedIndex = index
        })
                  const record = this.dataSource[this.selectedRowKeys[0]]
        if (null == record.auditStatus || '' == record.auditStatus || undefined == record.auditStatus) {
          this.$message.warning('该数据审核状态信息异常')
          return
        }
        if (record.auditStatus == "01" || record.auditStatus == "11" || record.auditStatus == "21"
          || record.auditStatus == "31" || record.auditStatus == "41") {
          this.$message.warning('该数据在审批流程中不能进行停用')
          return
        }
        if (record.auditStatus == "22") {
          this.$message.warning('该数据已是停用状态不能进行停用')
          return
        }
        if(record.auditStatus=="12"){
          this.$message.warning('该数据已注销不能进行停用')
          return
        }
        this.recordTemp = record
        this.modalText = '确定要停用商户等级代码为(' + record.mchntLevelCode + ')的限额吗？'
        this.stopShow = true

      },
      useMerchantGradeManager() {
        if (!this.selectedRowKeys.length) {
          this.$message.warning('请选择需要启用的记录')
          return;
        }
        if (this.selectedRowKeys.length > 1) {
          this.$message.warning('请选择一条需要启用的记录')
          return;
        }
        let selectedIndex = ''
        this.dataSource.map((val, index)=>{
          if(val.notDiffAcctId === this.selectedRowKeys[0]) return selectedIndex = index
        })
                  const record = this.dataSource[this.selectedRowKeys[0]]
        if (null == record.auditStatus || '' == record.auditStatus || undefined == record.auditStatus) {
          this.$message.warning('该数据审核状态信息异常')
          return
        }
        if (record.auditStatus == "01" || record.auditStatus == "11" || record.auditStatus == "21"
          || record.auditStatus == "31" || record.auditStatus == "41") {
          this.$message.warning('该数据在审批流程中不能进行启用')
          return
        }
        if (record.auditStatus != "33" && record.auditStatus != "22") {
          this.$message.warning('只允许启用“启用-审批拒绝”和“停用-审批通过”的数据')
          return
        }
        this.recordTemp = record
        this.modalText = '确定要启用商户等级代码为(' + record.mchntLevelCode + ')的限额吗？'
        this.useShow = true

      },
      cancelMerchantGradeManager() {
        if (!this.selectedRowKeys.length) {
          this.$message.warning('请选择需要注销的记录')
          return;
        }
        if (this.selectedRowKeys.length > 1) {
          this.$message.warning('请选择一条需要注销的记录')
          return;
        }
        let selectedIndex = ''
        this.dataSource.map((val, index)=>{
          if(val.notDiffAcctId === this.selectedRowKeys[0]) return selectedIndex = index
        })
                  const record = this.dataSource[this.selectedRowKeys[0]]
        let auditStatus = record.auditStatus
        if (null == auditStatus || '' == auditStatus || undefined == auditStatus) {
          this.$message.warning('该数据审核状态信息异常')
          return
        }
        if (auditStatus == "01" || auditStatus == "11" || auditStatus == "21" || auditStatus == "31" || auditStatus == "41") {
          this.$message.warning('该数据在审批流程中不能注销')
          return
        }
        if (auditStatus == "12") {
          this.$message.warning('该数据已注销不能进行注销')
          return
        }
        this.recordTemp = record
        this.modalText = '确定要注销商户等级代码为(' + record.mchntLevelCode + ')的限额吗？'
        this.cancelShow = true
      },

      stopOk() {
        // let param = {}
        // param.optFlag = 'stop'
      this.recordTemp.optFlag='stop'
        this.$put('/admin/quota/merchantGradeManager/stopMcGradeQuota', this.recordTemp).then((r) => {
          if(r.data.code!='100000'){
            this.stopShow = false;
            this.$message.error(r.data.message)
            this.search()
          }else {
            this.stopShow = false;
            this.$message.success('商户组别MCC限额停用操作成功')
            this.search()
          }

        }).catch(() => {
          this.loading = false
        })
      },
      useOk() {
        let param = {}
        this.recordTemp.optFlag = 'use'

        this.$put('/admin/quota/merchantGradeManager/startMcGradeQuota', this.recordTemp).then((r) => {

          if(r.data.code!='100000'){
            this.useShow = false;
            this.$message.error(r.data.message)
            this.search()
          }else {
            this.useShow = false;
            this.$message.success('商户组别MCC限额启用操作成功')
            this.search()
          }
        }).catch(() => {
          this.loading = false
        })
      },
      cancelOk() {
        let param = {}
        this.recordTemp.optFlag = 'cancel'

        this.$put('/admin/quota/merchantGradeManager/deleteMcGradeQuota', this.recordTemp).then((r) => {
          if(r.data.code!='100000'){
            this.cancelShow = false;
            this.$message.error(r.data.message)
            this.search()
          }else {
            this.cancelShow = false;
            this.$message.success('商户组别MCC限额注销操作成功')
            this.search()
          }
        }).catch(() => {
          this.loading = false
        })
      },
      handleCancel() {
        this.stopShow = false;
        this.useShow = false;
        this.cancelShow = false;
      },

      search() {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        let params = this.queryParams

        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
      },
      reset() {
        debugger
        // 取消选中
        this.selectedRowKeys = []
        // 重置分页
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }
        // 重置列排序规则
        this.sortedInfo = null
        // 重置查询参数
        // this.queryParams = {}
        // // 清空时间选择
        // this.$refs.createTime.reset()
                  this.queryParams.instId=''
                  // this.fetch()
      },
      handleTableChange(pagination, filters, sorter) {
                  this.selectedRowKeys = []
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        this.filteredInfo = filters
        this.sortedInfo = sorter
        // this.userInfo.visiable = false

        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        this.$get('/admin/quota/merchantGradeManager', {
          ...params
        }).then((r) => {
          let data = r.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
          this.loading = false
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  @import "../../../../../../static/less/Common";
</style>
